package com.controller;

import com.alibaba.druid.util.StringUtils;
import com.fesine.commons.util.CryptographyUtil;
import com.fesine.commons.util.DateUtils;
import com.fesine.commons.util.GenerateUUID;
import com.fesine.commons.util.ResponseUtils;
import com.po.UserInfoPo;
import com.services.UserInfoService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

    /**
     * @description: ⽤用户信息请求处理理
     * @author: Fesine
     * @createTime:2017/3/30 23:21
     * @update:修改内容
     * @author: Fesine
     * @updateTime:2017/3/30 23:21
     */
    @Controller
    @RequestMapping("/userInfo")
    public class UserInfoController {
        private static final Logger logger = Logger.getLogger(UserInfoController.class);
        @Autowired
        private UserInfoService userInfoService;
        public static long initTime;
        public static long loginTime;
        @Value("${upload.file.root}")
        private String uploadFileRoot;
        /**
         * 登录操作
         *
         * @param req
         * @param response
         */
        @RequestMapping(value = "/login", method = RequestMethod.POST)
        public void login(HttpServletRequest req, HttpServletResponse response
        ) {
            Map<String, Object> map = new HashMap<String, Object>();
            loginTime = System.currentTimeMillis();
            if (loginTime - initTime > 30000) {
                map.put("success", false);
                map.put("msg", "验证码过期，有效时间30秒!");
            } else {
                String userName = req.getParameter("userName");
                String captchaToken = ((String) req.getSession().getAttribute("captchaToken")).toLowerCase();
                String checkCode = req.getParameter("checkCode").toLowerCase();
                logger.info("----->captchaToken:" + captchaToken + ",checkCode:"+ checkCode);
//不不区          分⼤大⼩小写
                if (!captchaToken.equals(checkCode.toLowerCase())) {
                    map.put("success", false);
                    map.put("msg", "验证码错误!");
                } else {
                    UserInfoPo userInfoPo = new UserInfoPo();
                    userInfoPo.setUserName(userName);
                    userInfoPo = userInfoService.getUserInfo(userInfoPo);
                    if (userInfoPo != null) {
//⽤用户                 用户名正确，再验证密码
                        String password = req.getParameter("password");
                        if (CryptographyUtil.md5(password, "fesine").equals(userInfoPo.getPassword())) {
//创建⽤                    用户session
                            req.getSession().setAttribute("userName", userName);
                            req.getSession().setAttribute("nickName", userInfoPo.getNickName());
                            req.getSession().setAttribute("uploadFileRoot", uploadFileRoot);
                            map.put("success", true);
                            map.put("msg", "验证成功!");
                        } else {
                            map.put("success", false);
                            map.put("msg", "密码错误!");
                        }
                    } else {
                        map.put("success", false);
                        map.put("msg", "⽤用户名不不存在!");
                    }
                }
            }
            try {
                ResponseUtils.outPut(response, map);
            } catch (Exception e) {
                logger.error("", e);
            }
        }
        /**
         * 退出登录
         *
         * @param req
         * @param response
         * @throws Exception
         */
        @RequestMapping("/logout")
        public void logout(HttpServletRequest req, HttpServletResponse response)throws Exception {
            req.getSession().invalidate();
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("success", true);
            map.put("msg", "注销成功!");
            try {
                ResponseUtils.outPut(response, map);
            } catch (Exception e) {
                logger.error("", e);
            }
        }
        /**
         * 添加⽤用户信息
         *
         * @param req
         * @param response
         * @throws Exception
         */
        @RequestMapping(value = "/addUserInfo", method = RequestMethod.POST)
        public void addUserInfo(@RequestParam MultipartFile photos, HttpServletRequest req, HttpServletResponse response)
                throws Exception {
            UserInfoPo u = createUserInfo(req);
            u.setId(GenerateUUID.getUUId());
            Date date = new Date();
            u.setCreateTime(date);
            u.setUpdateTime(date);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("success", true);
            map.put("msg", "添加⽤用户信息成功!");
            try {
                if (photos.isEmpty()) {
                    logger.info("---->没有上传头像");
                    u.setHeadPhoto("default.jpg");
                } else {
                    String headPhoto = uploadPhotos(photos, req);
                    u.setHeadPhoto(headPhoto);
                }
                userInfoService.addUserInfo(u);
            } catch (Exception e) {
                logger.error("", e);
                map.put("success", false);
                map.put("msg", "添加⽤用户信息失败!");
            }
            try {
                ResponseUtils.outPut(response, map);
            } catch (Exception e) {
                logger.error("", e);
            }
        }
        /**
         * 修改⽤用户信息
         *
         * @param req
         * @param response
         * @throws Exception
         */
        @RequestMapping(value = "/updateUserInfo", method = RequestMethod
                .POST)
        public void updateUserInfo(@RequestParam MultipartFile photos,HttpServletRequest req, HttpServletResponse response)
                throws Exception {
            UserInfoPo u = createUserInfo(req);
            Date date = new Date();
            u.setUpdateTime(date);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("success", true);
            map.put("msg", "修改⽤用户信息成功!");
            try {
                if (!photos.isEmpty()){
                    String headPhoto = uploadPhotos(photos, req);
                    u.setHeadPhoto(headPhoto);
                }
                userInfoService.modifyUserInfo(u);
            } catch (Exception e) {
                logger.error("", e);
                map.put("success", false);
                map.put("msg", "修改⽤用户信息失败!");
            }
            try {
                ResponseUtils.outPut(response, map);
            } catch (Exception e) {
                logger.error("", e);
            }
        }
        /**
         * 修改⽤用户信息
         *
         * @param req
         * @param response
         * @throws Exception
         */
        @RequestMapping(value = "/updatePassword", method = RequestMethod.POST)
        public void updatePassword(HttpServletRequest req, HttpServletResponse response)
                throws Exception {
            UserInfoPo u = createUserInfo(req);
            Date date = new Date();
            u.setUpdateTime(date);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("success", true);
            map.put("msg", "修改密码成功!");
            try {
                userInfoService.modifyUserInfo(u);
            } catch (Exception e) {
                logger.error("", e);
                map.put("success", false);
                map.put("msg", "修改密码失败!");
            }
            try {
                ResponseUtils.outPut(response, map);
            } catch (Exception e) {
                logger.error("", e);
            }
        }
        @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
        public void uploadFile(@RequestParam MultipartFile photos, HttpServletRequest req,
                               HttpServletResponse response) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("success", true);
            map.put("msg", "上传⽂文件成功!");
            try {
                String headPhoto = this.uploadPhotos(photos,req);
                map.put("fileName", headPhoto);
            } catch (IOException e) {
                logger.error("",e);
                map.put("success", false);
                map.put("msg", "上传⽂文件失败!");
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                ResponseUtils.outPut(response, map);
            } catch (Exception e) {
                logger.error("", e);
            }
        }
        /**
         * 删除⽤用户信息
         *
         * @param req
         * @param response
         * @throws Exception
         */
        @RequestMapping(value = "/deleteUserInfo", method = RequestMethod.
                POST)
        public void deleteUserInfo(HttpServletRequest req, HttpServletResponse
                response)
                throws Exception {
            Map<String, Object> map = new HashMap<String, Object>();
            String userIds = req.getParameter("userIds").replace("\"", "");
            String[] IdsArr = userIds.split(",");
            map.put("success", true);
            map.put("msg", "删除⽤用户信息成功!");
            try {
                userInfoService.deleteUsers(IdsArr);
            } catch (Exception e) {
                logger.error("", e);
                map.put("success", false);
                map.put("msg", "删除⽤用户信息失败!");
            }
            try {
                ResponseUtils.outPut(response, map);
            } catch (Exception e) {
                logger.error("", e);
            }
        }
        /**
         * 查询⽤用户信息
         *
         * @param req
         * @param response
         * @throws Exception
         */
        @RequestMapping("/listUserInfo")
        public void listUserInfo(HttpServletRequest req, HttpServletResponse response)
                throws Exception {
            UserInfoPo u = createUserInfo(req);
            String offset = req.getParameter("start");
            String pageSize = req.getParameter("limit");
            if (!StringUtils.isEmpty(offset) && !StringUtils.isEmpty(pageSize)) {
                u.setOffset(Integer.parseInt(offset));
                u.setPageSize(Integer.parseInt(pageSize));
            }
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("success", true);
            map.put("msg", "查询⽤用户信息成功!");
            try {
                List<UserInfoPo> list = userInfoService.listUserInfo(u);
                int total = userInfoService.getTotal(u);
                map.put("userInfoList", list);
                map.put("total", total);
            } catch (Exception e) {
                logger.error("", e);
                map.put("success", false);
                map.put("msg", "查询⽤用户信息失败!");
            }
            try {
                ResponseUtils.outPut(response, map);
            } catch (Exception e) {
                logger.error("", e);
            }
        }
        /**
         * 将前端请求字段转换为UserInfoPo对象
         *
         * @param req
         * @return
         */
        private UserInfoPo createUserInfo(HttpServletRequest req) {
            UserInfoPo u = new UserInfoPo();
            u.setId(req.getParameter("id"));
            u.setUserName(req.getParameter("userName"));
            if (!StringUtils.isEmpty(req.getParameter("password")))
                u.setPassword(CryptographyUtil.md5(req.getParameter("password"
                ), "fesine"));
            u.setSex(req.getParameter("sex"));
            u.setNickName(req.getParameter("nickName"));
            u.setCellPhoto(req.getParameter("cellPhone"));
            u.setAddress(req.getParameter("address"));
            u.setHeadPhoto(req.getParameter("headPhoto"));
            u.setInfoDesc(req.getParameter("infoDesc"));
            return u;
        }
        /**
         * 上传头像⽂文件
         *
         * @param photos
         * @param req
         * @throws IOException
         */
        private String uploadPhotos(MultipartFile photos, HttpServletRequest req) throws Exception {
            String headPhoto;
            String fileName = DateUtils.formatDate(new Date(), "yyyyMMddHH mmsssss");
                    String root = ResponseUtils.getRootPath(req);
            String filePath = root + uploadFileRoot;
            String orgFileName = photos.getOriginalFilename();//源⽂文件名
            String fileType = orgFileName.substring(orgFileName.lastIndexOf("."
            ) + 1);
            fileName = "[" + fileType + "]" + fileName + "." + fileType;
            filePath = filePath + fileName;
            logger.info("------>上传⽂文件路路径:" + filePath);
            long startTime = System.currentTimeMillis(); //获取开始时间
            try {
//执⾏行行上传动作
                photos.transferTo(new File(filePath));
                headPhoto = fileName;
                long endTime = System.currentTimeMillis(); //获取结束时间
                logger.info("上传⽂文件共使⽤用时间：" + (endTime - startTime) + "毫秒");
                return headPhoto;
            } catch (Exception e) {
                logger.error("⽂文件上传失败", e);
                throw e;
            }
        }

}










